package tr.edu.metu.is550.isell.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import tr.edu.metu.is550.isell.R;
import tr.edu.metu.is550.isell.domain.Property;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class SearchPropertyActivity extends Activity {

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (Activity.RESULT_OK != resultCode)
            return;

        Double lat = (Double) data.getExtras().get("lat");
        Double lon = (Double) data.getExtras().get("lon");

        ((EditText) findViewById(R.id.txtLatitude)).setText(String.valueOf(lat));
        ((EditText) findViewById(R.id.txtLongitude)).setText(String.valueOf(lon));

    }

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_property);
        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

        Button btnSearchProperty = (Button) findViewById(R.id.btnSearchSubmit);
        Button btnShowMap = (Button) findViewById(R.id.btnShowMap);

        btnShowMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), MapsActivity.class);
                startActivityForResult(myIntent, 1);
            }
        });


        btnSearchProperty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String serverURL = sp.getString("pref_dialog", "NULL");

                    DefaultHttpClient client = new DefaultHttpClient();

                    String uri = serverURL + "/property";

                    Uri.Builder builder = Uri.parse(uri).buildUpon()
                            .appendQueryParameter("radius", ((EditText) findViewById(R.id.txtRadius)).getText().toString())
                            .appendQueryParameter("latitude", ((EditText) findViewById(R.id.txtLatitude)).getText().toString())
                            .appendQueryParameter("longitude", ((EditText) findViewById(R.id.txtLongitude)).getText().toString());

                    if (!((EditText) findViewById(R.id.txtMinPrice)).getText().toString().equals("")) {
                        builder.appendQueryParameter("minPrice", ((EditText) findViewById(R.id.txtMinPrice)).getText().toString());
                    }
                    if (!((EditText) findViewById(R.id.txtMaxPrice)).getText().toString().equals("")) {
                        builder.appendQueryParameter("maxPrice", ((EditText) findViewById(R.id.txtMaxPrice)).getText().toString());
                    }
                    if (!((EditText) findViewById(R.id.txtMinNumberOfRooms)).getText().toString().equals("")) {
                        builder.appendQueryParameter("minNumOfRooms", ((EditText) findViewById(R.id.txtMinNumberOfRooms)).getText().toString());
                    }
                    if (!((EditText) findViewById(R.id.txtMaxNumberOfRooms)).getText().toString().equals("")) {
                        builder.appendQueryParameter("maxNumOfRooms", ((EditText) findViewById(R.id.txtMaxNumberOfRooms)).getText().toString());
                    }

                    builder.appendQueryParameter("adType", ((RadioButton) findViewById(R.id.radio_rental)).isChecked() ? "0" : "1");
                    builder.appendQueryParameter("propertyType", ((RadioButton) findViewById(R.id.radio_flat)).isChecked() ? "1" : "0");

                    HttpGet httpGet = new HttpGet(builder.build().toString());

                    httpGet.setHeader("Content-Type", "application/json");
                    httpGet.setHeader("Accept", "application/json");

                    HttpResponse response = client.execute(httpGet);
                    if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                        throw new RuntimeException("An error occured during registration");
                    } else {
                        HttpEntity entity = response.getEntity();
                        String result = convertStreamToString(entity.getContent());
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject properties = jsonObject.getJSONObject("");
                        JSONArray propertyArray = properties.getJSONArray("properties");
                        if (propertyArray.length() == 0) {
                            Toast.makeText(getApplicationContext(), "No property found!", Toast.LENGTH_LONG).show();
                        } else {
                            ArrayList<Property> list = new ArrayList<Property>();
                            for (int i = 0; i < propertyArray.length(); i++) {
                                Property property = new Property(propertyArray.getJSONObject(i).getString("title"), propertyArray.getJSONObject(i).getLong("id"));
                                list.add(property);
                            }
                            Intent myIntent = new Intent(view.getContext(), ListPropertyActivity.class);
                            myIntent.putExtra("data", list);
                            startActivity(myIntent);
                        }

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    private static String convertStreamToString(InputStream is) {
        /*
        * To convert the InputStream to String we use the BufferedReader.readLine()
        * method. We iterate until the BufferedReader return null which means
        * there's no more data to read. Each line will appended to a StringBuilder
        * and returned as String.
        */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

}
